<?php
namespace app\demo\model;

use traits\model\SoftDelete;
use app\mogosdk\model\Mogo;
use app\demo\model\Tags as TagsModel;
class Plan extends Mogo
{
    use SoftDelete;
    protected $table = 'dp_xdk_plan';
    protected $autoWriteTimestamp = true;
    //添加打卡
    public function addPlan(){

        $data = request()->only(['title','is_public','is_free','tags']);

        // 验证
        $validate = new \app\demo\validate\Plan();
        $result =  $validate->check($data);

        if(!$result){
            return  json(['error'=>$validate->getError()],422);
        }

        //string
        $tags = explode(',',$data['tags']);

        // 校验标签
        foreach ($tags as $key=>&$tag){
            if(!TagsModel::get($tag)){
                unset($tags[$key]);
            };
        }

        if(count($tags)<=0) return json(['error'=>'标签数量至少一个'],404);

        // 标签处理
        $plan = self::create($data);  //plan_id
        $plan->Tags()->attach($tags,['create_time'=>time()]);

        return json($plan);
    }
    public function Tags(){
        return $this->belongsToMany('Tags','xdk_plan_tags');
    }


}
